package com.whoyx.jiebing.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Stone
 * @date 2021/7/14
 */
@Component
public class RedisCacheUtils {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 缓存基本的对象，Integer、String、实体类等
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public void setCacheObject(String key, Object value)
    {
        ValueOperations<String, Object> operation = redisTemplate.opsForValue();
        operation.set(key, value);
    }

    /**
     * 缓存基本的对象，Integer、String、实体类等
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public void setCacheObject(String key, Object value, Integer timeout, TimeUnit timeUnit) {
        ValueOperations<String, Object> operation = redisTemplate.opsForValue();
        operation.set(key, value, timeout, timeUnit);
    }

    /**
     * 获得缓存的基本对象(String)。
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public String getStringCacheObject(String key) {
        ValueOperations<String, Object> operation = redisTemplate.opsForValue();
        Object o = operation.get(key);
        if (o instanceof String) {
            return (String) o;
        }
        return null;
    }

    /**
     * 获得缓存的基本对象(Objcet)。
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public Object getCacheObject(String key) {
        ValueOperations<String, Object> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 获得缓存的基本对象(Integer)。
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public Integer getIntegerCacheObject(String key) {
        ValueOperations<String, Object> operation = redisTemplate.opsForValue();
        Object o = operation.get(key);
        if (o instanceof Integer) {
            return (Integer) o;
        }
        return null;
    }

    public Long incrInt(String key, Integer timeout, TimeUnit timeUnit) {
        ValueOperations<String, Object> operation = redisTemplate.opsForValue();
        Long ret = operation.increment(key, 1);
        redisTemplate.expire(key, timeout, timeUnit);
        return ret;
    }

    /**
     * 删除单个对象
     * @param key key
     */
    public void deleteObject(String key) {
        redisTemplate.delete(key);
    }
}
